package com.tgh.utils;

import android.opengl.GLES20;

import java.nio.FloatBuffer;

public class GLRect2D {
    
    public GLRect2D() {}
    
    public GLRect2D(float x,float y,float width,float height) {
        this.x=x;
        this.y=y;
        mWidth=width;
        mHeight=height;
        updateVertices();
    }
    
    public void resize(float x,float y,float width,float height) {
        if (isChange(this.x, x) || isChange(this.y, y) || 
             isChange(mWidth, width) || isChange(mHeight, height)) {
            this.x=x;
            this.y=y;
            mWidth=width;
            mHeight=height;
            updateVertices();
        }
    }
    
    public void moveTo(float x,float y) {
        if (isChange(this.x, x) || isChange(this.y, y)) {
            this.x=x;
            this.y=y;
            updateVertices();
        }
    }
    
    public void moveLeft(float distance) {
        if (isChange(distance, 0f)) {
            x-=distance;
            updateVertices();
        }
    }
    public void moveRight(float distance) {
      if (isChange(distance, 0f)) {
          x+=distance;
          updateVertices();
        }
    }
    public void moveUp(float distance) {
      if (isChange(distance, 0f)) {
          y-=distance;
          updateVertices();
        }
    }
    public void moveDown(float distance) {
      if (isChange(distance, 0f)) {
          y+=distance;
          updateVertices();
        }
    }
    
    public void draw() {
        if (vertexBuffer!=null) {
            GLES20.glVertexAttribPointer(GLShaderManager.GL_ATTRIBUTE_VERTEX, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);
            GLES20.glEnableVertexAttribArray(GLShaderManager.GL_ATTRIBUTE_VERTEX);
            GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
        }
    }
    
    private void updateVertices() {
        float[] vPoints={
                x,y,
                x+mWidth,y,
                x+mWidth,y+mHeight,
                x,y+mHeight
        };
        vertexBuffer = GLTools.makeFloatBuffer(vPoints);
    }
    
    private boolean isChange(float f1,float f2) {
        return Float.compare(f1, f2)!=0;
    }
    
    private FloatBuffer vertexBuffer;
    private float mWidth;
    private float mHeight;
    private float x;
    private float y;
    
}
